//
//  STWebViewController.m
//  SportHome
//
//  Created by stoneobs on 16/12/14.
//  Copyright © 2016年 stoneobs. All rights reserved.
//

#define SCREEN_HEIGHT  [UIScreen mainScreen].bounds.size.height
#define SCREEN_FRAME  [UIScreen mainScreen].bounds
#define SCREEN_WIDTH  [UIScreen mainScreen].bounds.size.width


#import "TMGInviteFriendViewController.h"
#import "STWebViewController.h"
#import <WebKit/WebKit.h>
#import "KLSharePresentController.h"
@interface TMGInviteFriendViewController ()<WKNavigationDelegate>
@property(nonatomic, strong) NSString             *urlStr;
@property(nonatomic, strong) NSString             *h5String;
@property(nonatomic, strong) WKWebView            *webView;
@property(nonatomic, strong) UIProgressView       *progressView;
@property(nonatomic, strong) UIView               *loadingView;
@end

@implementation TMGInviteFriendViewController

- (instancetype)initWithUrl:(NSString *)url
{
    self = [super init];
    if (self) {
        self.urlStr = url;
    }
    return self;
}
- (instancetype)initWithH5String:(NSString *)h5String{
    self = [super init];
    if (self) {
        self.h5String = h5String;
    }
    return self;
}
- (void)dealloc
{
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
    [self.webView removeObserver:self forKeyPath:@"title"];
}
#pragma mark --Geter And Setter
- (UIColor *)progressTintColor
{
    if (_progressTintColor) {
        return _progressTintColor;
    }
    return [UIColor orangeColor];
}
- (UIColor *)progressBackgroundColor
{
    if (_progressTintColor) {
        return _progressTintColor;
    }
    return [UIColor grayColor];
}
#pragma mark --vc生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"正在加载...";
    self.view.backgroundColor = [UIColor whiteColor];
    self.webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 64,UIScreenWidth, UIScreenHeight)];
    self.automaticallyAdjustsScrollViewInsets = NO;
    if ([self.webView.scrollView respondsToSelector:@selector(setContentInsetAdjustmentBehavior:)]) {
        [self.webView.scrollView setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentNever];
    }
    [self.view addSubview:self.webView];
    
    if (self.urlStr) {
        [self.webView loadRequest:[[NSURLRequest alloc] initWithURL:[NSURL URLWithString:self.urlStr]]];
    }
    if (self.h5String) {
        [self.webView loadHTMLString:self.h5String baseURL:nil];
    }
    
    self.webView.navigationDelegate = self;
    
    
    self.progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, 1)];
    self.progressView.backgroundColor = self.progressBackgroundColor;
    self.progressView.progressTintColor = self.progressTintColor;
    [self.view addSubview:self.progressView];
    
    if (!self.navigationController.navigationController.navigationBar.translucent) {
        self.progressView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 1);
        self.webView.height = self.webView.height - 64;
    }else{
        self.progressView.frame = CGRectMake(0, 64, SCREEN_WIDTH, 1);
        
    }
    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    [self.webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil];
    
    //菊花
    UIActivityIndicatorView * juhuaView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    [juhuaView startAnimating];
    self.loadingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 80, 80)];
    juhuaView.center = CGPointMake(_loadingView.frame.size.width/2, _loadingView.frame.size.width/2);
    self.loadingView.layer.cornerRadius = 15;
    self.loadingView.center = self.view.center;
    self.loadingView.backgroundColor = [UIColor grayColor];
    [self.loadingView addSubview:juhuaView];
    [self.view addSubview:self.loadingView];
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
}
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
}
- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}
#pragma mark --kvo
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
    if (object==self.webView&&[keyPath isEqualToString:@"estimatedProgress"]) {
        //NSLog(@"%f",self.webView.estimatedProgress);
        self.progressView.progress = self.webView.estimatedProgress;
        
    }
    if (object==self.webView&&[keyPath isEqualToString:@"title"]) {
        
        self.title = self.webView.title;
    }
}
#pragma mark --WKNavigationDelegate

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
    
    //完成
    self.loadingView.hidden = YES;
    if (self.forceTitle.length) {
        self.title = self.forceTitle;
    }
    
}
- (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error
{
    self.loadingView.hidden = YES;
    if (self.forceTitle.length) {
        self.title = self.forceTitle;
    }
    NSLog(@"%@",error);
    
    
}
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    NSString *strRequest = [navigationAction.request.URL.absoluteString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString * rule = @"http://jshjkd.com/gold/public/home/web/friend_rule.html";
    NSString * rank = @"http://jshjkd.com/gold/public/home/web/friend_ranking.html";
    NSString * share = @"http://jshjkd.com/gold/public/home/web/friend_ranking1.html";//分享
    if([strRequest isEqualToString:rule] || [strRequest isEqualToString:rank] || [strRequest isEqualToString:share]) {
        decisionHandler(WKNavigationActionPolicyCancel);//不允许跳转
        if ([strRequest isEqualToString:share]) {
            //弹出分享
            NSLog(@"点击了分享");
            KLSharePresentController * shareVc = [[KLSharePresentController alloc] initWithHandle:^(NSString *chosedIde) {
                if ([chosedIde isEqualToString:@"朋友圈"]) {
                    [self shareFriendCircle];
                }else{
                    [self shareToGoodFriend];
                }
            }];
            [self.navigationController presentViewController:shareVc animated:NO completion:nil];
            
        }else{
            NSString * title = @"活动细则";
            if ([strRequest isEqualToString:rank] ) {
                title = @"排行榜";
            }
            STWebViewController * webvc = [[STWebViewController alloc] initWithUrl:strRequest];
            webvc.progressBackgroundColor = [UIColor whiteColor];
            webvc.progressTintColor = TM_orangeColor;
            webvc.forceTitle = title;
            [self.navigationController pushViewController:webvc animated:YES];
        }
       
        
    } else {//截获页面里面的链接点击
        
        //do something you want
        decisionHandler(WKNavigationActionPolicyAllow);//允许跳转
    }
}
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error;
{
    
    self.loadingView.hidden = YES;
    NSLog(@"%@",error);
    if (self.forceTitle.length) {
        self.title = self.forceTitle;
    }
    
}
#pragma mark --Private Method
//微信朋友圈
- (void)shareFriendCircle{
    
//    SendMessageToWXReq  *req = [SendMessageToWXReq new];
//    req.text = wechatShareDesc;
//    req.bText = YES;
//    req.scene = WXSceneSession;
//    req.scene = WXSceneTimeline;
//    [WXApi sendReq:req];
    
    NSString * url = [NSString stringWithFormat:@"http://jshjkd.com/gold/public/home/web/friend?uid=%@",[STUserManger defult].userID];
    SendMessageToWXReq  *req = [SendMessageToWXReq new];
    req.scene = WXSceneTimeline;
    WXMediaMessage *urlMessage = [WXMediaMessage message];
    urlMessage.title = wechatShareDesc;
    //分享标题 urlMessage.description = kLinkDescription;//分享描述
    [urlMessage setThumbImage:[UIImage imageNamed:@"logo_release"]];//分享图片,使用SDK的setThumbImage方法可压缩图片大小
    //创建多媒体对象
    WXWebpageObject *webObj = [WXWebpageObject object];
    webObj.webpageUrl = url;//分享链接 //完成发送对象实例
    urlMessage.mediaObject = webObj;
    req.message = urlMessage; //发送分享信息
    [WXApi sendReq:req];
    

}
//微信好友
- (void)shareToGoodFriend{
    NSString * url = [NSString stringWithFormat:@"http://jshjkd.com/gold/public/home/web/share?tid=%@",[STUserManger defult].userID];
    SendMessageToWXReq  *req = [SendMessageToWXReq new];
    req.scene = WXSceneSession;
    WXMediaMessage *urlMessage = [WXMediaMessage message];
    urlMessage.title = wechatShareDesc;
    //分享标题 urlMessage.description = kLinkDescription;//分享描述
    [urlMessage setThumbImage:[UIImage imageNamed:@"logo_release"]];//分享图片,使用SDK的setThumbImage方法可压缩图片大小
    //创建多媒体对象
    WXWebpageObject *webObj = [WXWebpageObject object];
    webObj.webpageUrl = url;//分享链接 //完成发送对象实例
    urlMessage.mediaObject = webObj;
    req.message = urlMessage; //发送分享信息
    [WXApi sendReq:req];
}
@end

